package com.whut.monitor.controller;

import com.whut.monitor.util.SendMessageUtil;
import com.whut.monitor.vo.ResponseMsg;
import com.whut.monitor.websocket.PollWebSocketServlet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author dxd
 *         2017/9/18
 *         云计算Python接口
 */

@Controller
@RequestMapping("/dataAnalysis")
public class DataAnalysisController {

    @Autowired
    PollWebSocketServlet webSocketServlet;

    private String filePath = "";

    @RequestMapping("/uploadbin")
    @ResponseBody
    public ResponseMsg uploadbin(@RequestParam MultipartFile file, HttpServletRequest request) {
        ResponseMsg j = new ResponseMsg();
        if (file.isEmpty()) {
            j.setMsg("请选择要上传的文件！");
        } else {
            String originalFilename = file.getOriginalFilename();
            String fileBaseName = FilenameUtils.getBaseName(originalFilename);
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String dataStr = dateFormat.format(now);
            try {
                String genePicPath = request.getSession().getServletContext().getRealPath("/upload/python/");

                //把上传的文件放到服务器的文件夹下
                String saveFileName = dataStr + "_" +originalFilename;
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(genePicPath, saveFileName));
                filePath = genePicPath + "/"+ saveFileName;
                j.setSuccess(true);
                j.setMsg("上传成功！");
            } catch (Exception e) {
                j.setMsg(e.getMessage());
                e.printStackTrace();
            }
        }
        return j;
    }

    @RequestMapping("/result")
    @ResponseBody
    public String getResult() {
        String result = pythonRun(filePath);
        filePath = "";
        if ("".equals(result)) {
            result = "文件无结果输出或代码有语法错误！";
            return result;
        } else {
            return result;
        }
    }

    /**
     * java调用控制台进程来运行python脚本
     * @param path Python文件所在路径
     * @return 计算结果
     */
    public String pythonRun(String path) {
        StringBuilder output = new StringBuilder();
        // 计算结果
        try {
            Process pr = Runtime.getRuntime().exec("python " + path);
            InputStream inputStream = pr.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            SendMessageUtil.sendMessage("python", "开始云计算！", webSocketServlet);
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                SendMessageUtil.sendMessage("python", line, webSocketServlet);
                output.append(" ").append(line);
            }
            SendMessageUtil.sendMessage("python", "计算完成！", webSocketServlet);
            System.out.println("outputOut:" + output);
            inputStream.close();
            in.close();
            pr.waitFor();
            pr.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 计算错误
        try {
            Process pr = Runtime.getRuntime().exec("python " + path);
            InputStream errorStream = pr.getErrorStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(errorStream));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                SendMessageUtil.sendMessage("python", line, webSocketServlet);
                output.append(" ").append(line);
            }
            System.out.println("outputError:" + output);
            errorStream.close();
            in.close();
            pr.waitFor();
            pr.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return output.toString();
    }
}
